package com.sofwin.realm;

import com.sofwin.mapper.SysUserMapper;
import com.sofwin.pojo.SysUser;
import com.sofwin.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.List;

public class UserRealm extends AuthorizingRealm {

    private UserService service;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = principalCollection.getPrimaryPrincipal().toString();//获取登录名
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        SysUser user = new SysUser();
        user.setLoginAccount(userName);
        user = service.selectUser(user);
        info.addRole(String.valueOf(user.getRoleId()));
        List<String> permissions = service.selectUserPermissionByRoleId(user.getRoleId());
        info.addStringPermissions(permissions);//给当前主体增加权限
        return info;
    }


    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());
        boolean hasUserName = service.selectUserByName(username);
        if (!hasUserName){
            throw new UnknownAccountException();
        }
        SysUser user = new SysUser();
        user.setLoginAccount(username);
        user.setLoginPwd(password);
        boolean status = service.checkLogin(user);
        if (!status){
            throw new IncorrectCredentialsException();
        }

        return new SimpleAuthenticationInfo(username,password,"RealName");
    }



    /**
     * 将注入的service交给Spring，setter方法注入
     */
    public void setService(UserService service) {
        this.service = service;
    }
}
